// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.chips;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class Multiplexer implements Chip {
  public int ADDRESS = 0;
  public byte DATA = 0;
  public boolean DATA_ACTIVE = false;
  public boolean WR = false;
  public boolean REQ = false;  

  final int multiplexerMask;
  final Memory mem1;
  final Memory mem2;
  
  public Multiplexer(int bit, Memory mem1, Memory mem2) {
    this.multiplexerMask = (1 << (bit - 1));
    this.mem1 = mem1;
    this.mem2 = mem2;
  }
  
  public void update() {
    if (REQ) {
      if ((ADDRESS & multiplexerMask) == 0) {
        mem1.ADDRESS = ADDRESS;
        mem1.WR = WR;
        mem1.REQ = true;
        mem2.REQ = false;
        if (DATA_ACTIVE) mem1.DATA = DATA;
        if (mem1.DATA_ACTIVE) DATA = mem1.DATA;
      } else {
        mem2.ADDRESS = ADDRESS;
        mem2.WR = WR;
        mem2.REQ = true;
        mem1.REQ = false;
        if (DATA_ACTIVE) mem2.DATA = DATA;
        if (mem1.DATA_ACTIVE) DATA = mem2.DATA;
      }
    } else {
      mem1.REQ = false;
      mem2.REQ = false;
    }
  }
}
